package com.xingfly.service;

import com.xingfly.model.Notification;
import com.xingfly.repository.NotificationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by SuperS on 18/05/2017.
 *
 * @author SuperS
 */
@Service
public class NotificationService {
    @Autowired
    private NotificationRepository notificationRepository;
    //删除某个用户的所有消息
    public boolean deleteAllByUserId(Long uid) {
        boolean flag = false;
        Long allSender = notificationRepository.countNotificationsBySenderId(uid);
        Long allReceiver = notificationRepository.countNotificationsByReceiverId(uid);
        if (allSender > 0) {
            notificationRepository.deleteNotificationsBySenderId(uid);
            flag = true;
        }
        if (allReceiver > 0) {
            notificationRepository.deleteNotificationsByReceiverId(uid);
            flag = true;
        }
        return flag;
    }
    //分页查询某个用户的所有消息
    public Page<Notification> findNotificationsByUserId(Long id, Pageable pageable) {
        return notificationRepository.findNotificationsByReceiverId(id, pageable);
    }
    //根据状态(已读、未读)分页查询某个用户的所有消息
    public Page<Notification> findNotificationsByUserIdAndStatus(Long id, Integer status, Pageable pageable) {
        return notificationRepository.findNotificationsByReceiverIdAndStatus(id, status, pageable);
    }
    //查询用户的所有消息
    public Long countNotificationsByUserId(Long id) {
        return notificationRepository.countNotificationsByReceiverId(id);
    }
    //根据状态(已读、未读)查询用户的所有消息
    public Long countNotificationsByUserId(Long id, Integer read) {
        return notificationRepository.countNotificationsByReceiverIdAndStatus(id, read);
    }
    //根据消息id查询消息对象
    public Notification findById(Long id) {
        return notificationRepository.findOne(id);
    }
    //保存、创建 消息
    public Notification save(Notification notification) {
        return notificationRepository.save(notification);
    }
    //删除某个事件的所有消息
    public boolean deleteAllByEventId(Long eid) {
        if (notificationRepository.countNotificationsByEventId(eid) > 0) {
            notificationRepository.deleteNotificationsByEventId(eid);
            return true;
        }
        return false;
    }
    //删除某个时间点之前的所有消息（用于Notification的定时清理）
    public void deleteNotificationsByCreateTimeBefore(Date date) {
        notificationRepository.deleteNotificationsByCreateTimeBefore(date);
    }
}
